package edu.ufl.cise.sanitas.client;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import edu.ufl.cise.sanitas.client.proxy.Proxy;
import edu.ufl.cise.sanitas.types.comm.CreateNewAccountRequest;
import edu.ufl.cise.sanitas.types.comm.CreateNewAccountResponse;
import edu.ufl.cise.sanitas.types.comm.Request;
import edu.ufl.cise.sanitas.types.comm.Response;
import edu.ufl.cise.sanitas.types.comm.SigninRequest;
import edu.ufl.cise.sanitas.types.comm.SigninResponse;
import edu.ufl.cise.sanitas.types.data.Condition;
import edu.ufl.cise.sanitas.types.data.User;

public class Launcher extends Activity {
	private static final int DIALOG_LAUNCHER_ID = 0;
	private static final int DIALOG_CREATE_NEW_ACCOUNT_ID = 1;
	private static final int DIALOG_SIGN_IN_ID = 2;

	private static final int HANDLE_SIGNIN = 0;

	private Dialog dialog = null;
	

	private Proxy mProxy;
	private Context mCtx;

	private SharedPreferences preference;

	// Communication-related
	private ProgressDialog pd;
	private AlertDialog ad;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			Response response = (Response) msg.obj;
			switch (response.getStatus()) {
			case SUCCESS:
				Intent mIntent = new Intent();
				setResult(RESULT_OK, mIntent);

				User user = null;
				Condition[] conditionList = null;

				switch (response.getType()) {
				case CREATE_NEW_ACCOUNT:
					CreateNewAccountResponse cnar = (CreateNewAccountResponse) response;
					user = cnar.getUesr();
					break;
				case SIGN_IN:
					SigninResponse sr = (SigninResponse) response;
					user = sr.getUser();
					conditionList = sr.getConditionList();
					break;
				}

				Proxy.setConditionList(conditionList);
				Proxy.setUser(user);

				SharedPreferences.Editor editor = preference.edit();
				editor.putBoolean("hasSignin", true);
				editor.putString("Username", user.getName());
				editor.putInt("UserID", user.getUserId());
				editor.putString("Password", user.getPassword());
				editor.commit();

				finish();
				break;
			case FAIL:
				AlertDialog.Builder failBuilder = new AlertDialog.Builder(mCtx);
				failBuilder.setMessage("Sorry! An error has occurred: " + response.getErrmsg())
					.setPositiveButton(R.string.launcher_alertdialog_btn_ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface d, int which) {
							ad.cancel();
							if (dialog == null) showDialog(DIALOG_LAUNCHER_ID);
						}
						
					});
				ad = failBuilder.create();
				ad.show();
				break;
			case TIMEOUT:
				AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(mCtx);
				timeoutBuilder.setMessage("Sorry! We cannot connect to the server. Please try again later...")
					.setPositiveButton(R.string.launcher_alertdialog_btn_ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface d, int which) {
							ad.cancel();
							if (dialog == null) {
								showDialog(DIALOG_LAUNCHER_ID);
							}
						}
						
					});
				ad = timeoutBuilder.create();
				ad.show();
				break;
			}
		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mProxy = Proxy.getInstance();
		preference = getSharedPreferences("SanitasClient", MODE_PRIVATE);

		if (preference.contains("hasSignin")) {
			pd = ProgressDialog.show(this, "Signing in", "Please wait...");
			Request request = new SigninRequest(mProxy.getConnectionStatus(),
					preference.getString("Username", null), preference
							.getString("Password", null));
			mProxy.sendRequest(request, handler, 0);
		} else {
			showDialog(DIALOG_LAUNCHER_ID);
		}
		mCtx = this;
	}

	@Override
	public Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_LAUNCHER_ID:
			dialog = new Dialog(this);

			dialog.setContentView(R.layout.signinnotification);
			dialog.setTitle("Log in");

			Button launcherBtnSignin = (Button) dialog
					.findViewById(R.id.loginnoti_btn_signin);
			launcherBtnSignin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissDialog(DIALOG_LAUNCHER_ID);
					showDialog(DIALOG_SIGN_IN_ID);
				}

			});

			Button launcherBtnCreate = (Button) dialog
					.findViewById(R.id.loginnoti_btn_create);
			launcherBtnCreate.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissDialog(DIALOG_LAUNCHER_ID);
					showDialog(DIALOG_CREATE_NEW_ACCOUNT_ID);
				}

			});

			break;
		case DIALOG_CREATE_NEW_ACCOUNT_ID:
			dialog = new Dialog(this);

			dialog.setContentView(R.layout.createnewaccount);
			dialog.setTitle("New Account");

			Button createBtnReturn = (Button) dialog
					.findViewById(R.id.create_btn_return);
			createBtnReturn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissDialog(DIALOG_CREATE_NEW_ACCOUNT_ID);
					showDialog(DIALOG_LAUNCHER_ID);
				}

			});

			Button createBtnCreate = (Button) dialog
					.findViewById(R.id.create_btn_create);
			createBtnCreate.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					pd = ProgressDialog.show(dialog.getContext(),
							"Creating New Account", "Please wait...");

					String username = ((EditText) dialog
							.findViewById(R.id.create_edit_name)).getText()
							.toString();
					int age = Integer.parseInt(((EditText) dialog
							.findViewById(R.id.create_edit_age)).getText()
							.toString());
					String gender = ((RadioGroup) dialog
							.findViewById(R.id.create_radio_gender))
							.getCheckedRadioButtonId() == 0 ? "m" : "f";
					String password = ((EditText) dialog
							.findViewById(R.id.create_edit_password)).getText()
							.toString();
					User user = new User(username, password, gender, age);

					Request request = new CreateNewAccountRequest(mProxy
							.getConnectionStatus(), user);

					mProxy.sendRequest(request, handler, 0);
				}

			});

			break;
		case DIALOG_SIGN_IN_ID:
			dialog = new Dialog(this);

			dialog.setContentView(R.layout.signin);
			dialog.setTitle("Sign in");

			Button signinBtnSignin = (Button) dialog
					.findViewById(R.id.signin_btn_signin);
			signinBtnSignin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					pd = ProgressDialog.show(dialog.getContext(),
							"Signing in...", "Please wait...");

					String username = ((EditText) dialog
							.findViewById(R.id.signin_edit_name)).getText()
							.toString();
					String password = ((EditText) dialog
							.findViewById(R.id.signin_edit_password)).getText()
							.toString();

					Request request = new SigninRequest(mProxy.getConnectionStatus(),
							username, password);

					mProxy.sendRequest(request, handler, 0);
				}

			});

			Button signinBtnReturn = (Button) dialog
					.findViewById(R.id.signin_btn_return);
			signinBtnReturn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissDialog(DIALOG_SIGN_IN_ID);
					showDialog(DIALOG_LAUNCHER_ID);
				}

			});

			break;
		default:
			dialog = null;
		}
		return dialog;
	}

}